import * as Cesium from 'cesium';

class EditRoute {
  constructor(viewer, height, arr = [110, 40, 0]) {
    this.viewer = viewer;
    this.height = height;
    this.bottomPosList = []
    this.relativePosList = [{ x: 0, y: 0, z: 0 }];
    this.originXYZ = Cesium.Cartesian3.fromDegrees(arr[0], arr[1], arr[2]);
    this.RoutePrimitive = null;
    this.BoxPrimitiveList = null;
    this.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(arr[0], arr[1], arr[2]));
    console.log('modelMatrix->', this.modelMatrix);
    this.handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    this.drawBox(15.0);
    // 设置双击事件的回调函数
    this.handler.setInputAction((event) => {
      const cartesian = this.viewer.scene.pickPosition(event.position);
      // 获取经纬度坐标
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      const longitude = Cesium.Math.toDegrees(cartographic.longitude);
      const latitude = Cesium.Math.toDegrees(cartographic.latitude);
      // 创建一个点实体
      // const pointEntity = {
      //   position: Cesium.Cartesian3.fromDegrees(longitude, latitude, 0), // 点的经纬度和高度
      //   point: {
      //     pixelSize: 10,
      //     color: Cesium.Color.RED
      //   }
      // }
      // this.bottomPosList.push(pointEntity);
      // this.bottomPosList.forEach(element => {
      //   this.viewer.entities.add(element);
      // });
      // 根据经度差值，计算弧段长度
      const lonLength = this.getLonArcLength(arr[1], longitude - arr[0]);
      const latLength = this.getLatArcLength(arr[0], latitude - arr[1]);
      this.relativePosList.push(new Cesium.Cartesian3(lonLength, latLength - 0.0625, this.height));
      console.log('设置双击事件->', this.relativePosList);
      console.log('经度弧长：' + lonLength + ', 纬度弧长：' + latLength);
      this.drawRoute()
      this.drawPoint()
    }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
  }
  drawPoint () {
    // 中心坐标（经度：110, 纬度：40, 高度：0）
    const centerLongitude = 110.0;  // 经度
    const centerLatitude = 40.0;    // 纬度
    const centerHeight = 0.0;       // 高度

    // 将中心地理坐标转换为笛卡尔坐标
    const centerCartographic = Cesium.Cartographic.fromDegrees(centerLongitude, centerLatitude, centerHeight);
    console.log('地图的经纬度', centerCartographic);
    // console.log('centerCartographic->', centerCartographic);
    const centerCartesian = Cesium.Cartesian3.fromRadians(centerCartographic.longitude, centerCartographic.latitude, centerCartographic.height);
    console.log('centerCartesian->', centerCartesian);
    const centerCartesian2 = Cesium.Cartesian3.fromDegrees(110.0, 40.0, 0.0)
    console.log('centerCartesian2->', centerCartesian2);
    // 定义相对于中心坐标的多个点偏移量
    const points = [
      // Cesium.Cartesian3.add(centerCartesian, new Cesium.Cartesian3(0.0, 0.0, 100.0), new Cesium.Cartesian3()),  // 近地点，沿Z轴正向偏移
      Cesium.Cartesian3.add(centerCartesian, new Cesium.Cartesian3(100.0, 0.0, 0.0), new Cesium.Cartesian3()),  // 沿X轴正向偏移
      // Cesium.Cartesian3.add(centerCartesian, new Cesium.Cartesian3(-100.0, 0.0, 0.0), new Cesium.Cartesian3()), // 沿X轴负向偏移
      // Cesium.Cartesian3.add(centerCartesian, new Cesium.Cartesian3(0.0, 100.0, 0.0), new Cesium.Cartesian3()),  // 沿Y轴正向偏移
      // Cesium.Cartesian3.add(centerCartesian, new Cesium.Cartesian3(0.0, 0.0, -100.0), new Cesium.Cartesian3()),  // 沿Z轴负向偏移
      // Cesium.Cartesian3.add(centerCartesian, new Cesium.Cartesian3(0.0, -100.0, 0.0), new Cesium.Cartesian3())  // 沿Y轴负向偏移
    ];
    // 创建一个 PointPrimitiveCollection 来保存所有点
    const pointCollection = new Cesium.PointPrimitiveCollection();
    this.viewer.scene.primitives.add(pointCollection);
    // 将每个点添加到集合中
    points.forEach((point) => {
      pointCollection.add({
        position: point,
        modelMatrix: this.modelMatrix,
        color: Cesium.Color.YELLOW,  // 如果是X轴偏移，设置为黄色，否则设置为红色
        pixelSize: 10,
      });
    });
    console.log('pointCollection->', pointCollection);
  }
  updateHeight (height) {
    this.height = height;
    this.relativePosList.forEach(element => {
      element.z = this.height;
    });
    this.drawRoute()
  }
  getLonArcLength (latitude, longitudeDifference) {
    const deltaLambda = Cesium.Math.toRadians(longitudeDifference);
    const R = 6378137 / Math.sqrt(1 - 0.00669438 * Math.sin(Cesium.Math.toRadians(latitude)) ** 2);
    const arcLength = R * deltaLambda * Math.cos(Cesium.Math.toRadians(latitude));
    return arcLength;
  }
  getLatArcLength (longitude, latitudeDifference) {
    const deltaPhi = Cesium.Math.toRadians(latitudeDifference);
    const R = 6378137 / Math.sqrt(1 - 0.00669438 * Math.sin(Cesium.Math.toRadians(longitude)) ** 2);
    const arcLength = R * deltaPhi;
    return arcLength;
  }
  getLineArr () {
    let newArr = []
    let sphereInstances = [];
    // 起点到终点
    for (let i = 0; i < this.relativePosList.length - 1; i++) {
      newArr.push([this.relativePosList[i], this.relativePosList[i + 1]]);
      // 创建多个球体的实例
      console.log('item->', this.relativePosList[i]);
      const center1 = Cesium.Cartesian3.fromDegrees(110.00, 40.000, 0);
      const sphereInstance1 = new Cesium.GeometryInstance({
        geometry: new Cesium.SphereGeometry({
          radius: 1.0,
          vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
          // maximum: new Cesium.Cartesian3(10.0, 10.0, 10.0),
          // minimum: new Cesium.Cartesian3(-10.0, -10.0, -10.0)
        }),
        modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(center1),
        // modelMatrix: Cesium.Matrix4.IDENTITY,
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.WHITE)
        }
      });
      // 例如，使用相对尺度因子来控制
      sphereInstances.push(sphereInstance1);
    }
    // 创建Primitive并添加到场景中
    const primitive = new Cesium.Primitive({
      geometryInstances: sphereInstances,
      appearance: new Cesium.PerInstanceColorAppearance({
        flat: true,
        translucent: false
      })
    });
    this.viewer.scene.primitives.add(primitive);
    let newArr2 = []
    // 地面到天空
    for (let index = 1; index < this.relativePosList.length; index++) {
      newArr2.push([this.relativePosList[index].x, this.relativePosList[index].y, 0]);
      newArr2.push([this.relativePosList[index].x, this.relativePosList[index].y, this.height]);
    }
    return newArr.flat().map(obj => [obj.x, obj.y, obj.z]).flat().concat(newArr2.flat());
  }
  drawBox (edgeLength) {
    if (this.BoxPrimitiveList) {
      this.viewer.scene.primitives.remove(this.BoxPrimitiveList)
      this.BoxPrimitiveList = null
    }
    const baseMatrix = [
      0, 1, 2, 0, 2, 3,   // 底面
      4, 5, 6, 4, 6, 7,   // 顶面(4,4,4,4,4,4)
      0, 1, 5, 0, 5, 4,   // 前面(0,0,3,0,3,1)
      1, 2, 6, 1, 6, 5,   // 右面(1,1,4,1,4,2)
      2, 3, 7, 2, 7, 6,   // 后面(2,2,5,2,5,3)
      3, 0, 4, 3, 4, 7,   // 左面(3,-1,2,3,2,4)
    ]
    const base8Pos64Arr = [
      0.0, 0.0, 0.0,                          // 0
      edgeLength, 0.0, 0.0,                   // 1
      edgeLength, edgeLength, 0.0,            // 2
      0.0, edgeLength, 0.0,                   // 3
      0.0, 0.0, edgeLength,                   // 4
      edgeLength, 0.0, edgeLength,            // 5
      edgeLength, edgeLength, edgeLength,     // 6
      0.0, edgeLength, edgeLength,            // 7
    ]
    // 面的外观
    const appearance = new Cesium.PerInstanceColorAppearance({
      flat: true,
      translucent: true
    });
    // 定义分组数量
    const positions = new Cesium.GeometryAttribute({
      componentDatatype: Cesium.ComponentDatatype.DOUBLE,
      componentsPerAttribute: 3,
      values: base8Pos64Arr,
    });
    // 定义立方体的面（由顶点索引组成）
    const indices = new Uint16Array(baseMatrix);
    // 创建几何体
    const geometry = new Cesium.Geometry({
      attributes: { position: positions },
      indices: indices,
      primitiveType: Cesium.PrimitiveType.TRIANGLES,
      boundingSphere: Cesium.BoundingSphere.fromVertices(base8Pos64Arr),
    });
    // 创建几何实例
    this.BoxPrimitiveList = new Cesium.Primitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: geometry,
        modelMatrix: this.modelMatrix,
        attributes: { color: Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(0.0, 0.0, 1.0, 0.5)) }
      }),
      appearance: appearance,
      asynchronous: false
    })
    this.viewer.scene.primitives.add(this.BoxPrimitiveList)
  }
  drawRoute () {
    if (this.RoutePrimitive) {
      this.viewer.scene.primitives.remove(this.RoutePrimitive)
      this.RoutePrimitive = null
    }
    // 线的外观
    const linepma = new Cesium.PerInstanceColorAppearance({
      flat: true,
      translucent: false,
      renderState: {
        depthTest: { enabled: true },
        lineWidth: Math.min(5.0, this.viewer.scene.maximumAliasedLineWidth),
      },
      material: Cesium.Material.fromType('Color', { color: Cesium.Color.GRAY })
    })
    console.log('relativePosList->', this.relativePosList);
    // 当前数组
    let pos64Arr = this.getLineArr()
    const geometryAttribute = new Cesium.GeometryAttribute({
      componentDatatype: Cesium.ComponentDatatype.DOUBLE,
      componentsPerAttribute: 3,
      values: new Float64Array(pos64Arr)
    });
    let mygeometry = new Cesium.Geometry({
      attributes: {
        position: geometryAttribute
      },
      primitiveType: Cesium.PrimitiveType.LINES,
      boundingSphere: Cesium.BoundingSphere.fromVertices(pos64Arr)
    });
    console.log('mygeometry->', mygeometry);
    const geometryInstances = new Cesium.GeometryInstance({
      geometry: mygeometry,
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromCssColorString('#F7F7F7'))
      }
    })
    console.log('geometryInstances->', geometryInstances);
    this.RoutePrimitive = new Cesium.Primitive({
      geometryInstances: geometryInstances,
      appearance: linepma,
      modelMatrix: this.modelMatrix,
      asynchronous: false
    });
    this.viewer.scene.primitives.add(this.RoutePrimitive);
    console.log('RoutePrimitive->', this.RoutePrimitive);
  }
}

export default EditRoute;
